import 'dart:async';
import 'dart:typed_data';
import 'dart:convert';

// 导入Flutter核心UI组件库
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// 导入多图选择插件
import 'package:multi_image_picker_plus/multi_image_picker_plus.dart';

// 应用入口点
void main() => runApp(MaterialApp(
      home: const MyApp(), // 设置主页面为MyApp
      theme: ThemeData(
        colorSchemeSeed: Colors.deepOrange, // 设置主题色为深橙色
        brightness: Brightness.dark, // 使用深色主题
      ),
    ));

// 主应用组件，为StatefulWidget，允许状态管理
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

// 媒体资产元数据类
// 存储媒体资产的各种属性信息
class AssetMetadata {
  // 构造函数
  // @param filename 文件名
  // @param size 文件大小
  // @param height 高度
  // @param width 宽度
  // @param creationDate 创建日期
  // @param id 唯一标识符
  AssetMetadata({
    required this.filename,
    required this.size,
    required this.height,
    required this.width,
    required this.creationDate,
    required this.id,
  });

  final String filename; // 文件名
  final int? size; // 文件大小（字节）
  final int? height; // 高度（像素）
  final int? width; // 宽度（像素）
  final String? creationDate; // 创建日期
  final String? id; // 唯一标识符
}

// 应用的状态管理类
class _MyAppState extends State<MyApp> {
  // 存储选择的媒体资产列表
  List<Asset> images = <Asset>[];
  // 错误信息
  String _error = 'No Error Dectected';
  // 当前选中的媒体资产
  Asset? _selectedAsset;
  // 选中资产的元数据
  AssetMetadata? _assetMetadata;
  Image? _thumbnailImage;
  bool _isLoading = false;

  /// 加载媒体资源
  /// 使用MultiImagePicker.pickImages方法打开媒体选择器
  Future<void> _loadAssets() async {
    final ColorScheme colorScheme = Theme.of(context).colorScheme;

    List<Asset> resultList = <Asset>[];
    String error = 'No Error Dectected';

    // iOS平台专辑设置
    const AlbumSetting albumSetting = AlbumSetting(
      fetchResults: {
        // 用户库
        PHFetchResult(
          type: PHAssetCollectionType.smartAlbum,
          subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary,
        ),
        // 收藏夹
        PHFetchResult(
          type: PHAssetCollectionType.smartAlbum,
          subtype: PHAssetCollectionSubtype.smartAlbumFavorites,
        ),
        // 普通相册
        PHFetchResult(
          type: PHAssetCollectionType.album,
          subtype: PHAssetCollectionSubtype.albumRegular,
        ),
        // 自拍
        PHFetchResult(
          type: PHAssetCollectionType.smartAlbum,
          subtype: PHAssetCollectionSubtype.smartAlbumSelfPortraits,
        ),
        // 全景
        PHFetchResult(
          type: PHAssetCollectionType.smartAlbum,
          subtype: PHAssetCollectionSubtype.smartAlbumPanoramas,
        ),
        // 视频
        PHFetchResult(
          type: PHAssetCollectionType.smartAlbum,
          subtype: PHAssetCollectionSubtype.smartAlbumVideos,
        ),
      },
    );

    // 选择设置
    const SelectionSetting selectionSetting = SelectionSetting(
      min: 0, // 最小选择数量
      max: 3, // 最大选择数量
      unselectOnReachingMax: true, // 达到最大数量时是否自动取消选择
    );

    // 关闭设置
    const DismissSetting dismissSetting = DismissSetting(
      enabled: true, // 允许关闭
      allowSwipe: true, // 允许滑动关闭
    );

    // 主题设置
    final ThemeSetting themeSetting = ThemeSetting(
      backgroundColor: colorScheme.surface, // 背景色
      selectionFillColor: colorScheme.primary, // 选择填充色
      selectionStrokeColor: colorScheme.onPrimary, // 选择边框色
      previewSubtitleAttributes:
          const TitleAttribute(fontSize: 12.0), // 预览副标题属性
      previewTitleAttributes: TitleAttribute(
        foregroundColor: colorScheme.primary, // 预览标题颜色
      ),
      albumTitleAttributes: TitleAttribute(
        foregroundColor: colorScheme.primary, // 专辑标题颜色
      ),
    );

    // 列表设置
    const ListSetting listSetting = ListSetting(
      spacing: 5.0, // 间距
      cellsPerRow: 4, // 每行显示的单元格数量
    );

    // 资产设置
    const AssetsSetting assetsSetting = AssetsSetting(
      // 设置允许选择的媒体类型（视频和图片）
      supportedMediaTypes: {MediaTypes.video, MediaTypes.image},
    );

    // iOS特有设置
    final CupertinoSettings iosSettings = CupertinoSettings(
      fetch: const FetchSetting(album: albumSetting, assets: assetsSetting),
      theme: themeSetting,
      selection: selectionSetting,
      dismiss: dismissSetting,
      list: listSetting,
    );

    try {
      // 调用插件的pickImages方法打开媒体选择器
      resultList = await MultiImagePicker.pickImages(
        selectedAssets: images, // 传入已选择的资产，支持预选功能
        iosOptions: IOSOptions(
          doneButton: UIBarButtonItem(
              title: 'Confirm', tintColor: colorScheme.primary), // 确认按钮
          cancelButton: UIBarButtonItem(
              title: 'Cancel', tintColor: colorScheme.primary), // 取消按钮
          albumButtonColor: colorScheme.primary, // 专辑按钮颜色
          settings: iosSettings, // iOS特有设置
        ),
        androidOptions: AndroidOptions(
          maxImages: 10, // 最多可选择的图片数量
          hasCameraInPickerPage: true, // 在选择页面显示相机
          exceptMimeType: { MimeType.GIF, MimeType.PNG }, // 排除的媒体类型集合（修复类型错误：从单个ImageType改为Set<ImageType>）
          lightStatusBar: false, // 是否使用浅色状态栏
          startInAllView: true, // 是否从全部视图开始
          actionBarColor: colorScheme.errorContainer, // 操作栏颜色
          actionBarTitleColor: colorScheme.primary, // 操作栏标题颜色
          statusBarColor: colorScheme.inverseSurface, // 状态栏颜色
          actionBarTitle: "Select Photo11111", // 操作栏标题
          allViewTitle: "All Photos1111", // "全部"视图标题
          useDetailsView: false, // false 不使用详情视图  true 使用详情视图
          selectCircleStrokeColor: colorScheme.onTertiaryFixed, // 选择圆圈颜色
          selectionLimitReachedText: "12121212", // 达到选择限制时的提示文本 未生效
          textOnNothingSelected: "13131313", // 未选择任何内容时的提示文本 未生效
          backButtonDrawable: "返回", // 返回按钮图标 需要资源图标才可生效
          okButtonDrawable: "确认", // 确认按钮图标 需要资源图标才可生效
          autoCloseOnSelectionLimit: true, // 达到选择限制时是否自动关闭
        ),
        // HarmonyOS平台特有的配置选项
        ohosOptions: const OhosOptions(
          maxImages: 10, // 最多可选择的图片数量
          isPhotoTakingSupported: true, 
          exceptMimeType: { ImageType.JPEG }, // 排除的媒体类型集合
        ),
      );

      // 打印resultList的总体信息
      print(
          'MultiImagePickerPlusPlugin resultList: ${resultList.length} images selected');

      // 打印每个Asset的详细信息
      for (var i = 0; i < resultList.length; i++) {
        final asset = resultList[i];
        print('MultiImagePickerPlusPlugin Image $asset:');
        print('MultiImagePickerPlusPlugin identifier: ${asset.identifier}');
        print('MultiImagePickerPlusPlugin name: ${asset.name}');
        print('MultiImagePickerPlusPlugin width: ${asset.originalWidth}');
        print('MultiImagePickerPlusPlugin height: ${asset.originalHeight}');
        print('MultiImagePickerPlusPlugin isLandscape: ${asset.isLandscape}');
      }
    } on Exception catch (e) {
      // 捕获并处理所有异常
      error = e.toString();
      print('MultiImagePickerPlusPlugin resultList error: ${error}');
    }

    // 检查widget是否仍然在树中，如果已被移除则不执行后续操作
    if (!mounted) return;

    // 更新UI状态
    setState(() {
      images = resultList;
      _error = error;
    });
  }

  /// 手动请求缩略图的示例方法
  Future<void> _requestThumbnailManually(Asset asset) async {
    setState(() {
      _selectedAsset = asset;
      _isLoading = true;
      _thumbnailImage = null;
    });

    try {
      // 2. 调用requestThumbnail方法请求缩略图
      // 参数: identifier, width, height, quality
      bool isThumbnail = await MultiImagePicker.requestThumbnail(
          asset.identifier, 400, 400, 80);
      print('MultiImagePickerPlusPlugin:: isThumbnail:: ${isThumbnail}');

      bool isOriginal =
          await MultiImagePicker.requestOriginal(asset.identifier, 80);
      print('MultiImagePickerPlusPlugin:: isOriginal:: ${isOriginal}');

      var metadata = await MultiImagePicker.requestMetadata(asset.identifier);

      print('MultiImagePickerPlusPlugin:: 完整信息   -----------  start');
      print('MultiImagePickerPlusPlugin:: ====== EXIF信息(ExifMetadata) ======');
      print('MultiImagePickerPlusPlugin:: 图像宽度(imageWidth): ${metadata.exif.imageWidth}');
      print(
          'MultiImagePickerPlusPlugin:: 图像高度(imageLength): ${metadata.exif.imageLength}');
      print(
          'MultiImagePickerPlusPlugin:: 每个样本位数(bitsPerSample): ${metadata.exif.bitsPerSample}');
      print(
          'MultiImagePickerPlusPlugin:: 压缩方式(compression): ${metadata.exif.compression}');
      print(
          'MultiImagePickerPlusPlugin:: 光度解释(photometricInterpretation): ${metadata.exif.photometricInterpretation}');
      print(
          'MultiImagePickerPlusPlugin:: 图像方向(orientation): ${metadata.exif.orientation}');
      print(
          'MultiImagePickerPlusPlugin:: 每像素样本数(samplesPerPixel): ${metadata.exif.samplesPerPixel}');
      print(
          'MultiImagePickerPlusPlugin:: 平面配置(planarConfiguration): ${metadata.exif.planarConfiguration}');
      print(
          'MultiImagePickerPlusPlugin:: YCbCr子采样(YCbCrSubSampling): ${metadata.exif.ycbCrSubSampling}');
      print(
          'MultiImagePickerPlusPlugin:: YCbCr定位(YCbCrPositioning): ${metadata.exif.ycbCrPositioning}');
      print(
          'MultiImagePickerPlusPlugin:: X分辨率(XResolution): ${metadata.exif.xResolution}');
      print(
          'MultiImagePickerPlusPlugin:: Y分辨率(YResolution): ${metadata.exif.yResolution}');
      print(
          'MultiImagePickerPlusPlugin:: 分辨率单位(resolutionUnit): ${metadata.exif.resolutionUnit}');
      print(
          'MultiImagePickerPlusPlugin:: 条纹偏移量(stripOffsets): ${metadata.exif.stripOffsets}');
      print(
          'MultiImagePickerPlusPlugin:: 每条纹行数(rowsPerStrip): ${metadata.exif.rowsPerStrip}');
      print(
          'MultiImagePickerPlusPlugin:: 条纹字节数(stripByteCounts): ${metadata.exif.stripByteCounts}');
      print(
          'MultiImagePickerPlusPlugin:: JPEG交换格式(JPEGInterchangeFormat): ${metadata.exif.jpegInterchangeFormat}');
      print(
          'MultiImagePickerPlusPlugin:: JPEG交换格式长度(JPEGInterchangeFormatLength): ${metadata.exif.jpegInterchangeFormatLength}');
      print(
          'MultiImagePickerPlusPlugin:: 传递函数(transferFunction): ${metadata.exif.transferFunction}');
      print('MultiImagePickerPlusPlugin:: 白点(whitePoint): ${metadata.exif.whitePoint}');
      print(
          'MultiImagePickerPlusPlugin:: 原色色度(primaryChromaticities): ${metadata.exif.primaryChromaticities}');
      print(
          'MultiImagePickerPlusPlugin:: YCbCr系数(YCbCrCoefficients): ${metadata.exif.ycbCrCoefficients}');
      print(
          'MultiImagePickerPlusPlugin:: 参考黑白点(referenceBlackWhite): ${metadata.exif.referenceBlackWhite}');
      print('MultiImagePickerPlusPlugin:: 修改日期时间(dateTime): ${metadata.exif.dateTime}');
      print(
          'MultiImagePickerPlusPlugin:: 图像描述(imageDescription): ${metadata.exif.imageDescription}');
      print('MultiImagePickerPlusPlugin:: 作者(artist): ${metadata.exif.artist}');
      print('MultiImagePickerPlusPlugin:: 版权(copyright): ${metadata.exif.copyright}');
      print(
          'MultiImagePickerPlusPlugin:: Exif版本(exifVersion): ${metadata.exif.exifVersion}');
      print(
          'MultiImagePickerPlusPlugin:: Flashpix版本(flashpixVersion): ${metadata.exif.flashpixVersion}');
      print('MultiImagePickerPlusPlugin:: 色彩空间(colorSpace): ${metadata.exif.colorSpace}');
      print('MultiImagePickerPlusPlugin:: 伽马(gamma): ${metadata.exif.gamma}');
      print(
          'MultiImagePickerPlusPlugin:: 像素X尺寸(pixelXDimension): ${metadata.exif.pixelXDimension}');
      print(
          'MultiImagePickerPlusPlugin:: 像素Y尺寸(pixelYDimension): ${metadata.exif.pixelYDimension}');
      print(
          'MultiImagePickerPlusPlugin:: 组件配置(componentsConfiguration): ${metadata.exif.componentsConfiguration}');
      print(
          'MultiImagePickerPlusPlugin:: 每像素压缩位数(compressedBitsPerPixel): ${metadata.exif.compressedBitsPerPixel}');
      print(
          'MultiImagePickerPlusPlugin:: 用户注释(userComment): ${metadata.exif.userComment}');
      print(
          'MultiImagePickerPlusPlugin:: 相关声音文件(relatedSoundFile): ${metadata.exif.relatedSoundFile}');
      print(
          'MultiImagePickerPlusPlugin:: 原始拍摄日期时间(dateTimeOriginal): ${metadata.exif.dateTimeOriginal}');
      print(
          'MultiImagePickerPlusPlugin:: 数字化日期时间(dateTimeDigitized): ${metadata.exif.dateTimeDigitized}');
      print('MultiImagePickerPlusPlugin:: 子秒时间(subSecTime): ${metadata.exif.subSecTime}');
      print(
          'MultiImagePickerPlusPlugin:: 原始子秒时间(subSecTimeOriginal): ${metadata.exif.subSecTimeOriginal}');
      print(
          'MultiImagePickerPlusPlugin:: 数字化子秒时间(subSecTimeDigitized): ${metadata.exif.subSecTimeDigitized}');
      print(
          'MultiImagePickerPlusPlugin:: 曝光时间(exposureTime): ${metadata.exif.exposureTime}');
      print('MultiImagePickerPlusPlugin:: 光圈值(fNumber): ${metadata.exif.fNumber}');
      print(
          'MultiImagePickerPlusPlugin:: 曝光程序(exposureProgram): ${metadata.exif.exposureProgram}');
      print(
          'MultiImagePickerPlusPlugin:: 光谱灵敏度(spectralSensitivity): ${metadata.exif.spectralSensitivity}');
      print(
          'MultiImagePickerPlusPlugin:: 感光度(photographicSensitivity): ${metadata.exif.photographicSensitivity}');
      print('MultiImagePickerPlusPlugin:: 光电转换函数(oecf): ${metadata.exif.oecf}');
      print(
          'MultiImagePickerPlusPlugin:: 灵敏度类型(sensitivityType): ${metadata.exif.sensitivityType}');
      print(
          'MultiImagePickerPlusPlugin:: 标准输出灵敏度(standardOutputSensitivity): ${metadata.exif.standardOutputSensitivity}');
      print(
          'MultiImagePickerPlusPlugin:: 推荐曝光指数(recommendedExposureIndex): ${metadata.exif.recommendedExposureIndex}');
      print('MultiImagePickerPlusPlugin:: ISO速度(isoSpeed): ${metadata.exif.isoSpeed}');
      print(
          'MultiImagePickerPlusPlugin:: ISO速度纬度yyy(isoSpeedLatitudeyyy): ${metadata.exif.isoSpeedLatitudeyyy}');
      print(
          'MultiImagePickerPlusPlugin:: ISO速度纬度zzz(isoSpeedLatitudezzz): ${metadata.exif.isoSpeedLatitudezzz}');
      print(
          'MultiImagePickerPlusPlugin:: 快门速度值(shutterSpeedValue): ${metadata.exif.shutterSpeedValue}');
      print(
          'MultiImagePickerPlusPlugin:: 光圈值(apertureValue): ${metadata.exif.apertureValue}');
      print(
          'MultiImagePickerPlusPlugin:: 亮度值(brightnessValue): ${metadata.exif.brightnessValue}');
      print(
          'MultiImagePickerPlusPlugin:: 曝光补偿值(exposureBiasValue): ${metadata.exif.exposureBiasValue}');
      print(
          'MultiImagePickerPlusPlugin:: 最大光圈值(maxApertureValue): ${metadata.exif.maxApertureValue}');
      print(
          'MultiImagePickerPlusPlugin:: 主体距离(subjectDistance): ${metadata.exif.subjectDistance}');
      print(
          'MultiImagePickerPlusPlugin:: 测光模式(meteringMode): ${metadata.exif.meteringMode}');
      print('MultiImagePickerPlusPlugin:: 光源(lightSource): ${metadata.exif.lightSource}');
      print('MultiImagePickerPlusPlugin:: 闪光灯(flash): ${metadata.exif.flash}');
      print(
          'MultiImagePickerPlusPlugin:: 主体区域(subjectArea): ${metadata.exif.subjectArea}');
      print('MultiImagePickerPlusPlugin:: 焦距(focalLength): ${metadata.exif.focalLength}');
      print(
          'MultiImagePickerPlusPlugin:: 闪光能量(flashEnergy): ${metadata.exif.flashEnergy}');
      print(
          'MultiImagePickerPlusPlugin:: 空间频率响应(spatialFrequencyResponse): ${metadata.exif.spatialFrequencyResponse}');
      print(
          'MultiImagePickerPlusPlugin:: 焦平面X分辨率(focalPlaneXResolution): ${metadata.exif.focalPlaneXResolution}');
      print(
          'MultiImagePickerPlusPlugin:: 焦平面Y分辨率(focalPlaneYResolution): ${metadata.exif.focalPlaneYResolution}');
      print(
          'MultiImagePickerPlusPlugin:: 焦平面分辨率单位(focalPlaneResolutionUnit): ${metadata.exif.focalPlaneResolutionUnit}');
      print(
          'MultiImagePickerPlusPlugin:: 主体位置(subjectLocation): ${metadata.exif.subjectLocation}');
      print(
          'MultiImagePickerPlusPlugin:: 曝光指数(exposureIndex): ${metadata.exif.exposureIndex}');
      print(
          'MultiImagePickerPlusPlugin:: 感应方法(sensingMethod): ${metadata.exif.sensingMethod}');
      print('MultiImagePickerPlusPlugin:: 文件来源(fileSource): ${metadata.exif.fileSource}');
      print('MultiImagePickerPlusPlugin:: 场景类型(sceneType): ${metadata.exif.sceneType}');
      print('MultiImagePickerPlusPlugin:: CFA模式(cfaPattern): ${metadata.exif.cfaPattern}');
      print(
          'MultiImagePickerPlusPlugin:: 自定义渲染(customRendered): ${metadata.exif.customRendered}');
      print(
          'MultiImagePickerPlusPlugin:: 曝光模式(exposureMode): ${metadata.exif.exposureMode}');
      print(
          'MultiImagePickerPlusPlugin:: 白平衡(whiteBalance): ${metadata.exif.whiteBalance}');
      print(
          'MultiImagePickerPlusPlugin:: 数字变焦比(digitalZoomRatio): ${metadata.exif.digitalZoomRatio}');
      print(
          'MultiImagePickerPlusPlugin:: 35mm等效焦距(focalLengthIn35mmFilm): ${metadata.exif.focalLengthIn35mmFilm}');
      print(
          'MultiImagePickerPlusPlugin:: 场景拍摄类型(sceneCaptureType): ${metadata.exif.sceneCaptureType}');
      print(
          'MultiImagePickerPlusPlugin:: 增益控制(gainControl): ${metadata.exif.gainControl}');
      print('MultiImagePickerPlusPlugin:: 对比度(contrast): ${metadata.exif.contrast}');
      print('MultiImagePickerPlusPlugin:: 饱和度(saturation): ${metadata.exif.saturation}');
      print('MultiImagePickerPlusPlugin:: 锐度(sharpness): ${metadata.exif.sharpness}');
      print(
          'MultiImagePickerPlusPlugin:: 设备设置描述(deviceSettingDescription): ${metadata.exif.deviceSettingDescription}');
      print(
          'MultiImagePickerPlusPlugin:: 主体距离范围(subjectDistanceRange): ${metadata.exif.subjectDistanceRange}');
      print(
          'MultiImagePickerPlusPlugin:: 图像唯一ID(imageUniqueID): ${metadata.exif.imageUniqueID}');


      print('MultiImagePickerPlusPlugin:: ====== 设备信息(DeviceMetadata) ======');
      print('MultiImagePickerPlusPlugin:: 设备制造商(make): ${metadata.device.make}');
      print('MultiImagePickerPlusPlugin:: 设备型号(model): ${metadata.device.model}');
      print('MultiImagePickerPlusPlugin:: 设备软件版本(software): ${metadata.device.software}');
      print('MultiImagePickerPlusPlugin:: 制造商注释(makerNote): ${metadata.device.makerNote}');
      print(
          'MultiImagePickerPlusPlugin:: 相机所有者名称(cameraOwnerName): ${metadata.device.cameraOwnerName}');
      print(
          'MultiImagePickerPlusPlugin:: 机身序列号(bodySerialNumber): ${metadata.device.bodySerialNumber}');
      print(
          'MultiImagePickerPlusPlugin:: 镜头规格(lensSpecification): ${metadata.device.lensSpecification}');
      print('MultiImagePickerPlusPlugin:: 镜头制造商(lensMake): ${metadata.device.lensMake}');
      print('MultiImagePickerPlusPlugin:: 镜头型号(lensModel): ${metadata.device.lensModel}');
      print(
          'MultiImagePickerPlusPlugin:: 镜头序列号(lensSerialNumber): ${metadata.device.lensSerialNumber}');

      print('MultiImagePickerPlusPlugin:: ====== GPS信息(GpsMetadata) ======');
      print(
          'MultiImagePickerPlusPlugin:: GPS版本ID(gpsVersionID): ${metadata.gps.gpsVersionID}');
      print(
          'MultiImagePickerPlusPlugin:: GPS纬度参考(gpsLatitudeRef): ${metadata.gps.gpsLatitudeRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS纬度(gpsLatitude): ${metadata.gps.gpsLatitude}');
      print(
          'MultiImagePickerPlusPlugin:: GPS经度参考(gpsLongitudeRef): ${metadata.gps.gpsLongitudeRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS经度(gpsLongitude): ${metadata.gps.gpsLongitude}');
      print(
          'MultiImagePickerPlusPlugin:: GPS高度参考(gpsAltitudeRef): ${metadata.gps.gpsAltitudeRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS高度(gpsAltitude): ${metadata.gps.gpsAltitude}');
      print(
          'MultiImagePickerPlusPlugin:: GPS时间戳(gpsTimeStamp): ${metadata.gps.gpsTimeStamp}');
      print(
          'MultiImagePickerPlusPlugin:: GPS卫星(gpsSatellites): ${metadata.gps.gpsSatellites}');
      print('MultiImagePickerPlusPlugin:: GPS状态(gpsStatus): ${metadata.gps.gpsStatus}');
      print(
          'MultiImagePickerPlusPlugin:: GPS测量模式(gpsMeasureMode): ${metadata.gps.gpsMeasureMode}');
      print('MultiImagePickerPlusPlugin:: GPS精度因子(gpsDOP): ${metadata.gps.gpsDOP}');
      print(
          'MultiImagePickerPlusPlugin:: GPS速度参考(gpsSpeedRef): ${metadata.gps.gpsSpeedRef}');
      print('MultiImagePickerPlusPlugin:: GPS速度(gpsSpeed): ${metadata.gps.gpsSpeed}');
      print(
          'MultiImagePickerPlusPlugin:: GPS航向参考(gpsTrackRef): ${metadata.gps.gpsTrackRef}');
      print('MultiImagePickerPlusPlugin:: GPS航向(gpsTrack): ${metadata.gps.gpsTrack}');
      print(
          'MultiImagePickerPlusPlugin:: GPS图像方向参考(gpsImgDirectionRef): ${metadata.gps.gpsImgDirectionRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS图像方向(gpsImgDirection): ${metadata.gps.gpsImgDirection}');
      print(
          'MultiImagePickerPlusPlugin:: GPS地图数据(gpsMapDatum): ${metadata.gps.gpsMapDatum}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标纬度参考(gpsDestLatitudeRef): ${metadata.gps.gpsDestLatitudeRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标纬度(gpsDestLatitude): ${metadata.gps.gpsDestLatitude}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标经度参考(gpsDestLongitudeRef): ${metadata.gps.gpsDestLongitudeRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标经度(gpsDestLongitude): ${metadata.gps.gpsDestLongitude}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标方位参考(gpsDestBearingRef): ${metadata.gps.gpsDestBearingRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标方位(gpsDestBearing): ${metadata.gps.gpsDestBearing}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标距离参考(gpsDestDistanceRef): ${metadata.gps.gpsDestDistanceRef}');
      print(
          'MultiImagePickerPlusPlugin:: GPS目标距离(gpsDestDistance): ${metadata.gps.gpsDestDistance}');
      print(
          'MultiImagePickerPlusPlugin:: GPS处理方法(gpsProcessingMethod): ${metadata.gps.gpsProcessingMethod}');
      print(
          'MultiImagePickerPlusPlugin:: GPS区域信息(gpsAreaInformation): ${metadata.gps.gpsAreaInformation}');
      print(
          'MultiImagePickerPlusPlugin:: GPS日期戳(gpsDateStamp): ${metadata.gps.gpsDateStamp}');
      print(
          'MultiImagePickerPlusPlugin:: GPS差分(gpsDifferential): ${metadata.gps.gpsDifferential}');
      print(
          'MultiImagePickerPlusPlugin:: GPS水平定位误差(gpsHPositioningError): ${metadata.gps.gpsHPositioningError}');
      print(
          'MultiImagePickerPlusPlugin:: 互操作性索引(interoperabilityIndex): ${metadata.gps.interoperabilityIndex}');

      print('MultiImagePickerPlusPlugin:: 完整信息   -----------  end');
    } on AssetNotFoundException catch (e) {
      print('MultiImagePickerPlusPlugin:: 资产不存在: ${e.message}');
    } on PermissionDeniedException catch (e) {
      print('MultiImagePickerPlusPlugin:: 权限被拒绝: ${e.message}');
    } catch (e) {
      print('MultiImagePickerPlusPlugin:: 发生错误: $e');
    } finally {
      print('MultiImagePickerPlusPlugin:: _isLoading ${_isLoading}');
    }
  }

  /// 构建媒体资产的网格视图
  /// 以网格形式展示所有选择的媒体资产，点击可请求缩略图
  Widget _buildGridView() {
    return GridView.count(
      crossAxisCount: 3, // 每行显示3个资产
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return GestureDetector(
          onTap: () => _requestThumbnailManually(asset),
          child: AssetThumb(
            asset: asset,
            width: 300,
            height: 300,
          ),
        );
      }),
    );
  }

  /// 构建应用程序的UI界面
  /// Flutter框架的核心方法，定义了Widget的结构和外观
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 应用栏，包含标题
      appBar: AppBar(
        title: const Text('Plugin example app'), // 应用程序标题
      ),
      // 主体内容
      body: Column(
        children: <Widget>[
          // 显示错误信息
          Center(child: Text('Error: $_error')),
          // 选择图片按钮
          ElevatedButton(
            onPressed: _loadAssets, // 点击时调用_loadAssets方法
            child: const Text("Pick images"), // 按钮文本
          ),
          // 可滚动的网格视图，占据剩余空间
          Expanded(
            child: _buildGridView(),
          )
        ],
      ),
    );
  }
}
